﻿@using System.ComponentModel
@using AntDesign.TableModels
@using BlazorApp.Client.Api
@using Entitys.File
@using Entitys.Web
@using Newtonsoft.Json
@using Utils;
@inject MessageService _message
@inject FileAdminApi fileApi
<div>
    <div>
        <span>
            <Search Size="@InputSize.Large" Placeholder="请输入路径" EnterButton="true" @bind-Value="@_path" OnSearch="OnSearch" WrapperStyle="width:70%" />
        </span>
        <span><Button Type="@ButtonType.Dashed" @onclick="PreviousPage">上一页</Button></span>
        <span><Button Type="@ButtonType.Dashed" @onclick="()=>{_visibleDeletes=true;}">批量删除</Button></span>
        <span><Button Type="@ButtonType.Dashed" @onclick="()=>{_visibleCreateDirectory=true;}">新建文件夹</Button></span>
        <span>
            <Upload @attributes="attrs"
                    FileList="fileList"
                    Multiple
                    Action="@uploading"
                    ShowUploadList=false
                    BeforeAllUpload="HandleFileList"
                    OnChange="HandleChange">
                <Button Type="@ButtonType.Dashed" >上传文件</Button>
            </Upload>
        </span>
    </div>
    <div>
        <Table DataSource="data" ScrollY="600px" PageSize="10"
               @bind-SelectedRows="selectedFiles">
            <Selection />
            <AntDesign.Column @bind-Field="@context.Name" Width="350" />
            <AntDesign.Column @bind-Field="@context.LengthName" Width="180" />
            <AntDesign.Column @bind-Field="@context.Root" Width="120" />

            <ActionColumn Title="操作">
                @if (@context.IsFile)
                {
                    <Button Type="@ButtonType.Text" @onclick="()=>UpdateFile(context)">编辑</Button>
                    <Popconfirm Placement="@Placement.TopLeft" Title=@(context.Name+"将被您删除") OkText="删除" CancelText="取消" OnConfirm="()=>DelteFile(context)">
                        <Button Type="@ButtonType.Text">删除</Button>
                    </Popconfirm>
                    <Button Type="@ButtonType.Text" @onclick="()=>UpdateNameDirectory(context)">重命名</Button>
                    @if (@context.Name.EndsWith(".zip"))
                    {
                        <Button Type="@ButtonType.Text" @onclick="()=>ExtractToDirectoryZip(context)">解压</Button>
                    }
                }
                else
                {
                    <Button Type="@ButtonType.Text" @onclick="()=>OpenFolder(context)">打开</Button>
                    <Popconfirm Placement="@Placement.TopLeft" Title=@("文件夹："+context.Name+"将被您删除") OkText="删除" CancelText="取消" OnConfirm="()=>DeleteDirectory(context)">
                        <Button Type="@ButtonType.Text">删除</Button>
                    </Popconfirm>
                    <Button Type="@ButtonType.Text" @onclick="()=>UpdateNameDirectory(context)">重命名</Button>
                    <Button Type="@ButtonType.Text" @onclick="()=>CompressDirectoryZIP(context)">压缩</Button>
                }
            </ActionColumn>
        </Table>
    </div>
</div>
@*重命名弹窗*@
<Modal Title="重命名文件或者文件夹"
       Visible="@_visibleRenameFolders"
       OnOk="@UpdateNameDirectoryOK"
       OnCancel="()=>{_updateFileData=null;
                        _updateNewName=string.Empty;
                        _visibleRenameFolders=false;}">
    <Input Placeholder="请输入新文件夹名称" WrapperStyle="width: 200px;" @bind-Value="_updateNewName" />
</Modal>
@*编辑文件*@
<Modal Title="重命名文件或者文件夹"
       Visible="@_visibleUpdateFile"
       OnOk="@UpdateFileSave"
       OnCancel="()=>{_updateFileData=null;_updateFileContent=string.Empty;_visibleUpdateFile=false;}">
    <TextArea Rows="15" @bind-Value="_updateFileContent" />
</Modal>
@*批量删除确认框*@
<Modal Title="删除警告"
       Visible="@_visibleDeletes"
       OnOk="@DeleteBatches"
       OnCancel="()=>{_visibleDeletes=false;}">
    是否确认删除多个文件夹和文件
</Modal>
@*新建文件夹*@
<Modal Title="新建文件夹"
       Visible="@_visibleCreateDirectory"
       OnOk="()=>{_visibleCreateDirectory=false;}"
       OnCancel="()=>{_visibleCreateDirectory=false;}">
    <Form Model="@createDirectoryData"
          LabelColSpan="8"
          WrapperColSpan="16"
          OnFinish="CreateDirectory">
        <FormItem Label="文件夹名称：">
            <Input @bind-Value="@context.Name" />
        </FormItem>
        <FormItem WrapperColOffset="8" WrapperColSpan="16">
            <Button Type="@ButtonType.Primary" HtmlType="submit">
                创建
            </Button>
        </FormItem>
    </Form>
</Modal>
@code {
    Dictionary<string, object> attrs = new Dictionary<string, object>
    {
        {"Name", "files" },
        {"Multiple", true }
    };
    private string uploading
    {
        get
        {
            return "/api/File/CreateFile?path=" + _path;
        }
    }
    private List<FilesDto> data = new List<FilesDto>();
    /// <summary>
    /// 选择的数据
    /// </summary>
    private IEnumerable<FilesDto>? selectedFiles;
    private  string? _path { get; set; } = @"/";
    /// <summary>
    /// 重命名文件或者文件夹弹窗
    /// </summary>
    private bool _visibleRenameFolders = false;
    /// <summary>
    /// 编辑文件
    /// </summary>
    private bool _visibleUpdateFile = false;
    /// <summary>
    /// 批量删除对话框
    /// </summary>
    private bool _visibleDeletes = false;
    /// <summary>
    /// 编辑文件内容;
    /// </summary>
    private string? _updateFileContent;
    /// <summary>
    /// 编辑东西临时
    /// </summary>
    private FilesDto? _updateFileData = null;

    private bool _visibleCreateDirectory = false;
    private string? _updateNewName;
    class CreateDirectoryData
    {
        public string? Name { get; set; }
    }
    private CreateDirectoryData createDirectoryData = new CreateDirectoryData();
    List<UploadFileItem> fileList = new List<UploadFileItem>
    {
    };
    /// <summary>
    /// 初始化
    /// </summary> <summary>
    protected override async void OnInitialized()
    {
        await GetFileData();
    }
    /// <summary>
    ///
    /// </summary>
    /// <returns></returns>
    private async Task OnSearch()
    {
        await GetFileData();
    }
    bool HandleFileList(List<UploadFileItem> fileItems)
    {
        return true;
    }
    void HandleChange(UploadInfo fileinfo)
    {
        if(fileList.Count > 2)
        {
            fileList.RemoveRange(0, fileList.Count - 2);
        }
        fileList.Where(file => file.State == UploadState.Success && !string.IsNullOrWhiteSpace(file.Response)).ForEach(file =>
        {
            Console.WriteLine(file.FileName);
        });
    }

    /// <summary>
    /// 新建文件夹
    /// </summary>
    private async void CreateDirectory(EditContext create)
    {
        var result = await fileApi.CreateDirectory(_path, createDirectoryData.Name!);
        _visibleCreateDirectory = false;
        if (result.StatusCode == 200)
        {
            await _message.Success("创建完成");
        }
        await GetFileData();
    }
    /// <summary>
    /// 压缩文件夹
    /// </summary>
    /// <param name="files"></param>
    /// <returns></returns>
    private async Task CompressDirectoryZIP(FilesDto files)
    {
        var data = await fileApi.CompressDirectoryZIP(files.Path);
        if (data.StatusCode == 200)
        {
            await GetFileData();
        }
    }
    /// <summary>
    /// 解压zip文件
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    public async Task ExtractToDirectoryZip(FilesDto file)
    {
        var data = await fileApi.ExtractToDirectoryZip(file.Path);
        if (data.StatusCode == 200)
        {
            await GetFileData();
        }
    }
    /// <summary>
    /// 删除文件
    /// </summary>
    /// <param name="files"></param>
    /// <returns></returns>
    public async Task DelteFile(FilesDto files)
    {
        var data = await fileApi.DeleteFile(files.Path);
        await GetFileData();
    }
    /// <summary>
    /// 批量删除
    /// </summary>
    private async void DeleteBatches()
    {
        var paths = selectedFiles.Select(a => new DeleteAllDto { Path = a.Path, IsFile = a.IsFile }).ToList();
        var data = await fileApi.DeleteAll(paths);
        await GetFileData();
        if (data.StatusCode == 200)
        {
            await _message.Success("删除成功");
        }
        _visibleDeletes = false;
    }
    /// <summary>
    /// 上一页
    /// </summary>
    private async Task PreviousPage()
    {
        var path = _path.Split("/");
        path = path.Take(path.Length - 1).ToArray();
        _path = string.Join("/", path);
        if (string.IsNullOrEmpty(_path)) _path = "/";
        await GetFileData();
    }
    /// <summary>
    /// 编辑文件
    /// </summary>
    /// <param name="files"></param>
    private async Task UpdateFile(FilesDto files)
    {
        var name = files.Name;
        if (!FormatTemplate.TextType.Any(a => name!.EndsWith(a)))
        {
            await _message.Warning("文件不能被编辑");
            return;
        }
        var content = await fileApi.GetFileContent(files.Path!);
        if (content.StatusCode != 200) return;
        if (string.IsNullOrEmpty(content.Data)) return;
        _visibleUpdateFile = true;
        _updateFileData = files;
        _updateFileContent = content.Data;
    }
    /// <summary>
    /// 保存文件
    /// </summary>
    /// <returns></returns>
    private async Task UpdateFileSave()
    {
        await fileApi.UpdateFileContent(_updateFileData.Path!, _updateFileContent!);
        _updateFileData = null;
        _updateFileContent = string.Empty;
        _visibleUpdateFile = false;
        await GetFileData();
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="files"></param>
    public void UpdateNameDirectory(FilesDto files)
    {
        _updateNewName = files.Name;
        _visibleRenameFolders = true;
        _updateFileData = files;
    }
    /// <summary>
    /// 编辑文件夹名称
    /// </summary>
    /// <returns></returns>
    public async Task UpdateNameDirectoryOK()
    {
        if (string.IsNullOrEmpty(_updateNewName))
        {
            await _message.Warning("新名称不能为空");
            return;
        }
        ModelStateResult<bool>? result;
        if (_updateFileData.IsFile)
        {
            result = await fileApi.UpdateNameFile(_updateFileData.Path, _updateNewName);
        }
        else
        {
            result = await fileApi.UpdateNameDirectory(_updateFileData.Path, _updateNewName);
        }
        _updateNewName = string.Empty;
        _updateFileData = null;
        _visibleRenameFolders = false;
        if (result.StatusCode == 200)
        {
            await GetFileData();
            await _message.Success("编辑成功");
        }
        else
        {
        }
    }
    /// <summary>
    /// 删除文件夹
    /// </summary>
    /// <param name="files"></param>
    /// <returns></returns>
    public async Task DeleteDirectory(FilesDto files)
    {
        var data = await fileApi.DeleteDirectory(files.Path);
        await GetFileData();
    }
    /// <summary>
    /// 打开文件夹
    /// </summary>
    /// <param name="files"></param>
    public async Task OpenFolder(FilesDto files)
    {
        var path = _path;
        _path = files.Path;
        if (!await GetFileData())
        {
            _path = path;
        }
    }
    /// <summary>
    /// 加载文件列表
    /// </summary>
    /// <returns></returns>
    private async Task<bool> GetFileData()
    {
        var list = await fileApi.GetFileData(_path);
        if (list.StatusCode == 200)
        {
            data.Clear();
            data.AddRange(list.Data);
            StateHasChanged();
            return true;
        }
        return false;
    }
    private async Task OnEnter(KeyboardEventArgs e)
    {
        await GetFileData();
    }

}
